from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.permissions import IsAuthenticated


from .models import Goods, GoodsCategory
from .serializers import GoodsSerializer, GoodsCategorySerializer, GoodsFilter
from django_filters import rest_framework as filters


class StandardResultsSetPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'
    page_query_param = 'p'
    max_page_size = 100


class GoodsViewSet(viewsets.ReadOnlyModelViewSet):
    """
    商品列表
    商品详情
    """
    queryset = Goods.objects.all()
    # 序列化
    serializer_class = GoodsSerializer
    # 分页
    pagination_class = StandardResultsSetPagination
    # 过滤
    filter_backends = (filters.DjangoFilterBackend, SearchFilter, OrderingFilter)
    filterset_class = GoodsFilter
    ordering_fields = ('add_time', )
    search_fields = ('name', 'goods_desc')
    #Token认证
    permission_classes = (IsAuthenticated,)


class GoodsCategorySet(viewsets.ReadOnlyModelViewSet):
    """
    商品种类列表
    """
    queryset = GoodsCategory.objects.filter(category_type=1)
    serializer_class = GoodsCategorySerializer

